"""
MQTT模型
"""

import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import paho.mqtt.subscribe as subscribe
import threading, time


sub_pool = []
pub_pool = []


class MQTT_client():

        def __init__(self):
                self.client = mqtt.Client()
                self.host = 'localhost'
                self.port = 1883

        def test(self):
                pass

        # 单播
        # def broad_one(self, topic, payload):
        #     msg = {'topic': topic, 'payload': payload}
        #     publish.multiple(msgs=msg, hostname=self.host)

        def publish(self):
                while True:
                        if pub_pool:
                                msg = pub_pool
                                print(msg)
                                publish.multiple(msgs=msg, hostname='0.0.0.0')
                                pub_pool.clear()
                        else:
                                time.sleep(0.3)

        def __callback(self, client, userdata, message):
                print('id:', message.mid, message.topic + ':' + message.payload.decode())

        def subscribe(self, topic):
                subscribe.callback(callback=self.__callback, topics=topic)

        def run(self, listen_topic):
                self.client.connect_async(host=self.host, port=self.port)
                self.client.loop_start()

                t1 = threading.Thread(target=self.publish)
                t2 = threading.Thread(target=self.subscribe, args=listen_topic)
                t1.setDaemon(True)
                t1.start()
                t2.start()


# if __name__ == '__main__':
#         t1 = threading.Thread(target=MQTT_client)
#         t1.setDaemon(True)
#         t1.start()
#         client = MQTT_client()
#         client.run(listen_topic='#')

